package com.monkey.web.shiro.web.filter.authc;

import com.monkey.core.web.response.MonkeyResponseDto;
import com.monkey.core.web.response.ResponseCode;
import com.monkey.utils.WebUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


/**
 * 1.登陆失败后把已经的对象存放到request中
 *
 * @author silentwu
 */
public class AppFormAuthenticationFilter extends FormAuthenticationFilter {


    /**
     * 处理用户已经登陆
     */
    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        if (subject.isAuthenticated()) {
            MonkeyResponseDto responseDto = new MonkeyResponseDto();
            responseDto.success(ResponseCode.LOGIN_REPEAT, "用户已经登录，不需要重复登录");
            WebUtils.writeJSON(response, responseDto);
            return false;
        }
        return super.onPreHandle(request, response, mappedValue);
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        MonkeyResponseDto responseDto = new MonkeyResponseDto();
        responseDto.success(ResponseCode.LOGIN_SUCCESS, "用户登录成功");
        WebUtils.writeJSON(response, responseDto);
        return false;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
//        e.printStackTrace();
        MonkeyResponseDto responseDto = new MonkeyResponseDto();
//        responseDto.fail(ResponseCode.LOGIN_FAIL, "用户名或密码错误");
        responseDto.fail(ResponseCode.LOGIN_FAIL, e.getMessage());
        WebUtils.writeJSON(response, responseDto);
        return false;
    }


}
